﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using _1Dot9MasterBiz;
using _1Dot9MasterTransactions;
using System.Net;
using System.Net.Sockets;

namespace _1Dot9MasterCommon
{
    /// <summary>
    /// 로그 기록 클래스
    /// </summary>
    public class CommonLogger
    {
        // 사용자 IP
        private string clientIP = string.Empty;        
        private string requestUrl = string.Empty;

        // Request URL 세팅
        public string RequestURL
        {
            set
            {
                this.requestUrl = value;
            }
        }

        /// <summary>
        /// Log를 기록합니다. 
        /// </summary>
        /// <param name="bizType">BizType.Custom</param>
        /// <param name="message">메시지</param>
        /// <param name="messageDetail">메시지상세</param>
        /// <param name="throwEx">Exception발생 시 다시 Throw할것인지 여부</param>
        public static void LogException(string message, string messageDetail, bool throwEx)
        {
            try
            {
                using (ExceptionLogBiz biz = new ExceptionLogBiz())
                {
                    biz.InsertLog(GetUserIp(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message, messageDetail);
                }
            }
            catch (Exception ex)
            {
                if (throwEx)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 메서드 명을 가지고 온다. 
        /// </summary>
        /// <returns></returns>
        public static string GetMethodName()
        {
            string msg = string.Empty;
            StackFrame stackFrame = new StackFrame(2, false);            
            MethodBase methodBase = stackFrame.GetMethod();
            msg += methodBase.DeclaringType.FullName + "->";
            msg += methodBase.Name + "()";
            return msg;
        }

        public static string GetUserIp()
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            string ipAddr = string.Empty;
            for (int i = 0; i < host.AddressList.Length; i++)
            {
                if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddr = host.AddressList[i].ToString();
                }
            }

            return ipAddr;
        }
    }
}
